package com.sys.platform.common.socket;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocket {

    public static int onlineCount = 0;
    public static Map<String, WebSocket> clients = new HashMap<>();
    public Session session;
    public String  username;
    public Long userId;
    public Long getUserId() {
        return userId;
    }

    @OnOpen
    public void onOpen(@PathParam("userId") Long userId, Session session){
        this.userId = userId;
        this.session = session;
        addOnlineCount();
        clients.put(session.getId(), this);
        log.warn("已连接:"+userId);
    }

    @OnClose
    public void onClose() throws IOException {
        log.warn("断开"+userId);
        clients.remove(session.getId());
        subOnlineCount();
    }

    //收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message) throws IOException {
        if(message.equals("ping")) {
            this.session.getAsyncRemote().sendText("pang");
        }else if("close".equals(message)) {
            onClose();
            this.session.close();
        }else {
            log.warn(this.userId+"收到 "+message);
        }
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public static void sendMessageTo(WebSocketDTO dto) {
        log.info("webSocket sendMsg:"+dto);
        for (WebSocket item : clients.values()) {
//            if (!dto.isAll() && !dto.getUserIdList().contains(item.getUserId())){
//                continue;
//            }
            item.session.getAsyncRemote().sendText(dto.getMsg());
        }
    }

    public static void clearMessageFromOpen(String message) {
        try {
            JSONObject json = JSONObject.parseObject(message);
            if(json.get("uuid") != null) {
            }
        } catch (Exception e) {
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }

}
